package com.vcms.utility.loader.storage.engine.xml.impl;

import org.w3c.dom.Element;

import com.vcms.entity.store.item.CashStoreItem;
import com.vcms.entity.store.itemtype.Coin;
import com.vcms.exception.VMCSException;
import com.vcms.utility.loader.storage.engine.xml.XmlStorageEngine;

/**
 * @author robin.foe A0092657U
 * Bridge design pattern concrete implementor
 */
public class CashXmlStorageEngine extends XmlStorageEngine<CashStoreItem>{
	
	public static final String ELEMENT_TAG_COIN = "coin";
	public static final String ELEMENT_TAG_NAME = "name";
	public static final String ELEMENT_TAG_VALUE = "value";
	public static final String ELEMENT_TAG_WEIGHT = "weight";
	public static final String ELEMENT_TAG_QUANTITY = "quantity";
	
	public CashXmlStorageEngine(String fileName) throws VMCSException {
		super(fileName,ELEMENT_TAG_COIN);
	}

	@Override
	public CashStoreItem getItem(int pk) {
		Element element = super.getElementByPk(pk);
		if(element == null)
			return null;
		
		Coin coin = new Coin();
		coin.setName(super.getValue(element, ELEMENT_TAG_NAME));
		coin.setValue( Integer.parseInt(super.getValue(element, ELEMENT_TAG_VALUE)) );
		coin.setWeight(Double.parseDouble( super.getValue(element, ELEMENT_TAG_WEIGHT) ));
		return new CashStoreItem(coin, Integer.parseInt( super.getValue(element, ELEMENT_TAG_QUANTITY) ));
	}

	@Override
	public void setItem(int pk, CashStoreItem storeItem) {
		Element element = super.getElementByPk(pk);
		if(element == null)
			return;
		
		Coin coin = (Coin)storeItem.getContent();
		element.getElementsByTagName(ELEMENT_TAG_NAME).item(0).setTextContent(coin.getName());
		element.getElementsByTagName(ELEMENT_TAG_VALUE).item(0).setTextContent(String.valueOf(coin.getValue()));
		element.getElementsByTagName(ELEMENT_TAG_WEIGHT).item(0).setTextContent(String.valueOf(coin.getWeight()));
		element.getElementsByTagName(ELEMENT_TAG_QUANTITY).item(0).setTextContent(String.valueOf(storeItem.getQuantity()));
	}

}
